//
//  KLProgressHUD.m
//  hud
//
//  Created by admin on 16/2/2.
//  Copyright © 2016年 静持大师. All rights reserved.
//

#import "KLProgressHUD.h"

#define keyPath(objc,keyPath) @(((void)objc.keyPath, #keyPath))
#define HUD_COLOR [UIColor colorWithWhite:0.0 alpha:0.8] // HUD颜色

static CGFloat const kMargin = 15.0f;   // HUD 间距

static NSTimeInterval const kSuccessOrFailHudDefultDelay = 1.5f;
static NSTimeInterval const kPromptHUDDefultDelay = 1.0f;

static CGFloat const kFontSize = 13.0f; // 文字大小

static NSString * const kSuccessImageName = @"hud_success.png";
static NSString * const kFailImageName = @"hud_fail.png";
static NSString * const kErrorImageName = @"hud_fail.png";
//static NSString * const kErrorImageName = @"hud_error.png";

@interface KLProgressHUD ()
/** msg */
@property (nonatomic, copy) NSString *title;
@end

@implementation KLProgressHUD

//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
+ (nullable instancetype)showWaitingHUD; {
    return [self showWaitingHUDWithSuperView:nil message:nil];
}

+ (nullable instancetype)showWaitingHUDWithSuperView:(nullable UIView *)superView {
    return [self showWaitingHUDWithSuperView:superView message:nil];
}

+ (nullable instancetype)showWaitingHUDWithMessage:(nullable NSString *)message {
    return [self showWaitingHUDWithSuperView:nil message:message];
}

+ (nullable instancetype)showWaitingHUDWithSuperView:(nullable UIView *)superView message:(nullable NSString *)message {
    KLProgressHUD *hudView = nil;
    
    if (superView == nil) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        hudView = [KLProgressHUD showHUDAddedTo:window animated:YES];
        
    }else {
        hudView = [KLProgressHUD showHUDAddedTo:superView animated:YES]; 
    }
    
    if (message.length != 0) {
        hudView.labelText = message;
    }
    
    hudView.userInteractionEnabled = YES;
    hudView.labelFont       = [UIFont systemFontOfSize:kFontSize];
    hudView.backgroundColor = [UIColor clearColor];
    hudView.color           = HUD_COLOR;
    hudView.margin          = kMargin;
    hudView.animationType   = MBProgressHUDAnimationFade;
    hudView.mode            = MBProgressHUDModeCustomView;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hud_loading.png"]];
    imageView.frame = CGRectMake(0, 0, 64, 35);
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0];
    rotationAnimation.duration = 1.5;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    rotationAnimation.removedOnCompletion = NO;
    
    [imageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
    hudView.customView = imageView;
    
    hudView.removeFromSuperViewOnHide = YES;
    hudView.animationType = MBProgressHUDAnimationFade;
    
    return hudView;
}

//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
+ (nullable instancetype)showPromptHUDWithMessage:(nonnull NSString *)message {
    return [KLProgressHUD showPromptHUDWithSuperView:nil
                                      message:message
                                      andTime:kPromptHUDDefultDelay
                                    completed:nil];
}

+ (nullable instancetype)showPromptHUDWithMessage:(nonnull NSString *)message andTime:(float)sec {
    return [KLProgressHUD showPromptHUDWithSuperView:nil
                                      message:message
                                      andTime:sec
                                    completed:nil];

}

+ (nullable instancetype)showPromptHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message {
    return [KLProgressHUD showPromptHUDWithSuperView:superView
                                      message:message
                                      andTime:kPromptHUDDefultDelay
                                    completed:nil];
}

+ (nullable instancetype)showPromptHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message andTime:(float)sec {
    return [KLProgressHUD showPromptHUDWithSuperView:superView
                                      message:message
                                      andTime:sec
                                    completed:nil];
}

+ (nullable instancetype)showPromptHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message completed:(nullable Completed)completed {
    return [KLProgressHUD showPromptHUDWithSuperView:superView
                                      message:message
                                      andTime:kPromptHUDDefultDelay
                                    completed:completed];
}

+ (nullable instancetype)showPromptHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message andTime:(float)sec completed:(nullable Completed)completed {
    if (sec == 0) {
        sec = kPromptHUDDefultDelay;
    }
    
    KLProgressHUD *messageHud = nil;

    if (superView == nil) {
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        messageHud = [KLProgressHUD showHUDAddedTo:window animated:YES];
    
    }else {
        messageHud = [KLProgressHUD showHUDAddedTo:superView animated:YES];
    }
    
    messageHud.userInteractionEnabled = NO;
    messageHud.color            = HUD_COLOR;
    messageHud.mode             = MBProgressHUDModeText;
    messageHud.labelText        = message;
    messageHud.labelFont        = [UIFont systemFontOfSize:kFontSize];
    messageHud.margin           = kMargin;
    messageHud.animationType    = MBProgressHUDAnimationFade;
    messageHud.removeFromSuperViewOnHide = YES;
    
    [messageHud hide:YES afterDelay:sec];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((sec + 0.1) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (completed) {
            completed();
        }
    });
    
    return messageHud;
}

//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
// 成功
+ (void)showSuccessHUDWithMessage:(nonnull NSString *)message {
    [self showStatusHUDWithSuperView:nil
                     statusImageName:kSuccessImageName
                             message:message
                         isHudEnable:NO
                             andTime:kSuccessOrFailHudDefultDelay
                           completed:nil];
}

+ (void)showSuccessHUDWithMessage:(NSString *)message isHudEnable:(BOOL)isHudEnable {
    [self showStatusHUDWithSuperView:nil
                     statusImageName:kSuccessImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:kSuccessOrFailHudDefultDelay
                           completed:nil];
}

+ (void)showSuccessHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable{
    [self showStatusHUDWithSuperView:superView
                     statusImageName:kSuccessImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:kSuccessOrFailHudDefultDelay
                           completed:nil];
}

+ (void)showSuccessHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable andTime:(float)sec {
    [self showStatusHUDWithSuperView:superView
                     statusImageName:kSuccessImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:sec
                           completed:nil];
}

+ (void)showSuccessHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable completed:(nullable Completed)completed {
    [self showStatusHUDWithSuperView:superView
                     statusImageName:kSuccessImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:kSuccessOrFailHudDefultDelay
                           completed:completed];

}

+ (void)showSuccessHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable andTime:(float)sec completed:(nullable Completed)completed {
    [self showStatusHUDWithSuperView:superView
                     statusImageName:kSuccessImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:sec
                           completed:completed];
}

// 错误
+ (void)showErrorHUDWithMessage:(nonnull NSString *)message {
    [self showStatusHUDWithSuperView:nil
                     statusImageName:kFailImageName
                             message:message
                         isHudEnable:NO
                             andTime:kSuccessOrFailHudDefultDelay
                           completed:nil];

}

+ (void)showErrorHUDWithMessage:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable {
    [self showStatusHUDWithSuperView:nil
                     statusImageName:kFailImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:kSuccessOrFailHudDefultDelay
                           completed:nil];
}

+ (void)showErrorHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable {
    [self showStatusHUDWithSuperView:superView
                     statusImageName:kFailImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:kSuccessOrFailHudDefultDelay
                           completed:nil];
}

+ (void)showErrorHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable andTime:(float)sec {
    [self showStatusHUDWithSuperView:superView
                     statusImageName:kFailImageName
                                   message:message
                               isHudEnable:isHudEnable
                                   andTime:sec
                                 completed:nil];
}

+ (void)showErrorHUDWithSuperView:(nullable UIView *)superView message:(nonnull NSString *)message isHudEnable:(BOOL)isHudEnable andTime:(float)sec completed:(nullable Completed)completed {
    [self showStatusHUDWithSuperView:superView
                     statusImageName:kFailImageName
                             message:message
                         isHudEnable:isHudEnable
                             andTime:sec
                           completed:completed];
}

+ (void)showErrorHUDWithError:(nullable NSError *)error {
    [self showErrorHUDWithSuperView:nil
                              error:error
                            andTime:kSuccessOrFailHudDefultDelay];
}

+ (void)showErrorHUDWithSuperView:(nullable UIView *)superView error:(nullable NSError *)error {
    [self showErrorHUDWithSuperView:superView
                              error:error
                            andTime:kSuccessOrFailHudDefultDelay];
}

+ (void)showErrorHUDWithSuperView:(nullable UIView *)superView error:(nullable NSError *)error andTime:(float)sec {
    
    NSString *message = nil;
    
    if (error == nil) {
        message = @"未知错误";
    }else {
        switch (error.code) {
            case kNoHUDErrorCode:                   message = nil; break;
            case NSURLErrorCancelled:               message = nil; break;
                
            case NSURLErrorTimedOut:                message = @"网络超时"; break;
            case NSURLErrorUnsupportedURL:          message = @"不支持的URL"; break;
            case NSURLErrorCannotFindHost:          message = @"找不到主机"; break;
            case NSURLErrorCannotConnectToHost:     message = @"不能连接到主机"; break;
            case NSURLErrorNetworkConnectionLost:   message = @"网络连接丢失"; break;
            case NSURLErrorDNSLookupFailed:         message = @"DNS解析错误"; break;
            case NSURLErrorHTTPTooManyRedirects:    message = @"重定向错误"; break;
            case NSURLErrorNotConnectedToInternet:  message = @"无法连接网路"; break;
            case NSURLErrorCannotParseResponse:     message = @"无法解析响应数据"; break;
                
            default:
                message = [NSString stringWithFormat:@"网络错误(错误码:%@)", @(error.code)];
                break;
        }
    }
    
    if (message != nil) {
        [self showStatusHUDWithSuperView:superView
                         statusImageName:kErrorImageName
                                 message:message
                             isHudEnable:NO
                                 andTime:sec
                               completed:nil];
    }
}

+ (void)showStatusHUDWithSuperView:(nullable UIView *)superView
                   statusImageName:(nonnull NSString *)statusImageName
                           message:(nonnull NSString *)message
                       isHudEnable:(BOOL)isHudEnable
                           andTime:(float)sec
                         completed:(nullable Completed)completed {
    
    KLProgressHUD *statusView = nil;
    
    if (superView == nil) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        statusView = [KLProgressHUD showHUDAddedTo:window animated:YES];
    }else {
        statusView = [KLProgressHUD showHUDAddedTo:superView animated:YES];
    }
    
    statusView.userInteractionEnabled = isHudEnable;
    statusView.color = HUD_COLOR;
    statusView.margin        = kMargin;
    statusView.labelText     = message;
    statusView.labelFont = [UIFont systemFontOfSize:kFontSize];
    statusView.animationType = MBProgressHUDAnimationFade;
    statusView.customView    = [[UIImageView alloc] initWithImage:[UIImage imageNamed:statusImageName]];
    statusView.mode          = MBProgressHUDModeCustomView;
    statusView.removeFromSuperViewOnHide = YES;

    [statusView hide:YES afterDelay:sec];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((sec + 0.1) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (completed) {
            completed();
        }
    });
}

#pragma mark - 原生
+ (void)showAlertViewWithTitle:(NSString *)title {
    if ([NSString app_isBlankString:title]) {
        title = @"未知异常";
    }
    [self showAlertViewWithTitle:title message:nil];
}

+ (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message {
    [[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil] show];
}

@end
